<template>
	<div class="wrapper">
		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">确认放贷</h1>
				</section>
			</div>
		</header>

		<!-- 借贷信息部分 -->
		<h3>借贷信息：</h3>
		<div class="loan-info">
			<p>借贷金额：<span class="amount">¥{{ loanAmount || '0.00' }}</span></p>
			<p class="interest-info">每日利率：{{ (dailyInterestRate * 100).toFixed(3) }}%</p>
			<p class="interest-info">预计每日利息：¥{{ estimatedDailyInterest }}</p>
			<p class="warning-info" v-if="!loanAmount || loanAmount < 1">借贷金额无效，请返回重新输入</p>
		</div>

		<!-- 提示信息 -->
		<div class="notice-card">
			<div class="notice-content">
				<i class="material-icons">info</i>
				<p>确认放贷后，金额将立即到账到您的钱包余额</p>
			</div>
		</div>

		<div class="payment-button">
			<button 
				type="button"
				@click.stop="confirmLoan" 
				:disabled="loading || !loanAmount || loanAmount < 1"
			>
				<span v-if="loading">放贷中...</span>
				<span v-else-if="!loanAmount || loanAmount < 1">金额无效</span>
				<span v-else>确认放贷 ¥{{ loanAmount.toFixed(2) }}</span>
			</button>
		</div>

		<!-- 底部菜单部分 -->
		<AppFooter></AppFooter>
	</div>
</template>

<script>
	import AppFooter from '../components/AppFooter.vue';
	import BackButton from '../components/BackButton.vue';
	export default {
		name: 'LoanPayment',
		data(){
			return {
				loanAmount: 0,
				dailyInterestRate: 0.001, // 默认0.1%
				loading: false,
				user: null
			}
		},
		computed: {
			estimatedDailyInterest() {
				if (!this.loanAmount || this.loanAmount < 1) return '0.00';
				const interest = this.loanAmount * this.dailyInterestRate;
				return interest.toFixed(2);
			}
		},
		created() {
			let user = this.$getSessionStorage('user');
			if (!user) {
				this.$toast?.error('请先登录');
				this.$router.push('/login');
				return;
			}
			this.user = user;

			// 从路由参数获取借贷金额
			const amount = parseFloat(this.$route.query.amount);
			if (!amount || isNaN(amount) || amount < 1) {
				this.$toast?.error('借贷金额无效');
				setTimeout(() => {
					this.$router.go(-1);
				}, 1500);
				return;
			}
			this.loanAmount = amount;

			// 加载借贷规则
			this.loadLoanRules();
		},
		mounted() {
			// 防止用户通过返回键回到借贷页面
			history.pushState(null, null, document.URL);
			window.onpopstate = () => {
				this.$router.push({path: '/myWallet'});
			}
		},
		unmounted() {
			window.onpopstate = null;
		},
		methods: {
			loadLoanRules() {
				// 从后端获取透支规则（利息率等）
				this.$axios.post('WalletRuleController/getRechargeRule').then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200') && response.data.result) {
						const rule = response.data.result;
						this.dailyInterestRate = parseFloat(rule.dailyInterestRate || 0.001);
					}
				}).catch(error => {
					console.error('获取借贷规则失败:', error);
				});
			},
			confirmLoan(event) {
				// 阻止默认行为和事件冒泡
				if (event) {
					event.preventDefault();
					event.stopPropagation();
				}
				
				if (this.loading) {
					return;
				}
				
				if (!this.user || !this.user.userId) {
					this.$toast?.error('用户信息错误，请重新登录');
					this.$router.push('/login');
					return;
				}
				
				if (!this.loanAmount || this.loanAmount < 1) {
					this.$toast?.error('借贷金额无效');
					return;
				}
				
				// 直接调用借贷接口
				this.loading = true;
				if (this.$toast) {
					this.$toast.info('正在处理放贷...');
				}
				
				// 调用借贷接口
				const requestData = {
					walletId: this.user.userId,
					amount: this.loanAmount
				};
				
				this.$axios.post('wallet/borrow', this.$qs.stringify(requestData), {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				}).then(response => {
						if (response && response.data) {
							const code = response.data.code;
							const isSuccess = code === 200 || code === '200' || response.status === 200;
							
							if (isSuccess) {
								const successMsg = `借贷成功！已到账 ¥${this.loanAmount.toFixed(2)}`;
								
								if (this.$toast) {
									this.$toast.success(successMsg);
								} else {
									alert(successMsg);
								}
								
								// 触发全局事件，通知MyWallet组件刷新余额
								try {
									if (window.dispatchEvent) {
										const event = new CustomEvent('wallet-balance-updated', {
											bubbles: true,
											cancelable: true
										});
										window.dispatchEvent(event);
									}
								} catch (e) {
									console.warn('触发事件失败:', e);
								}
								
								// 延迟跳转，让用户看到成功提示
								setTimeout(() => {
									this.loading = false;
									// 再次触发事件确保余额刷新
									if (window.dispatchEvent) {
										window.dispatchEvent(new CustomEvent('wallet-balance-updated'));
									}
									this.$router.push({ path: '/myWallet' }).catch(err => {
										console.error('路由跳转失败:', err);
										this.loading = false;
									});
								}, 2000);
							} else {
								const errorMsg = response.data?.message || response.data?.msg || '借贷失败，请重试';
								console.error('借贷失败:', errorMsg);
								if (this.$toast) {
									this.$toast.error(errorMsg);
								} else {
									alert(errorMsg);
								}
								this.loading = false;
							}
						} else {
							console.error('响应数据格式错误:', response);
							if (this.$toast) {
								this.$toast.error('服务器响应异常，请重试');
							} else {
								alert('服务器响应异常，请重试');
							}
							this.loading = false;
						}
					}).catch(error => {
						console.error('借贷接口调用失败:', error);
						
						// 提取错误信息
						let errorMsg = '借贷失败，请稍后重试';
						if (error.response) {
							if (error.response.data) {
								errorMsg = error.response.data.message || error.response.data.msg || errorMsg;
							} else if (error.response.status) {
								if (error.response.status === 404) {
									errorMsg = '接口不存在，请检查网络连接';
								} else if (error.response.status === 500) {
									errorMsg = '服务器错误，请稍后重试';
								} else {
									errorMsg = `请求失败 (${error.response.status})`;
								}
							}
						} else if (error.message) {
							errorMsg = error.message;
						}
						
						if (this.$toast) {
							this.$toast.error(errorMsg);
						} else {
							alert(errorMsg);
						}
						this.loading = false;
					});
			}
		},
		components: {
			AppFooter,
			BackButton
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 借贷信息部分 ******************/
	.wrapper h3 {
		margin-top: 0;
		box-sizing: border-box;
		padding: 16px 16px 8px;
		font-size: 14px;
		font-weight: 500;
		color: #666;
		background-color: #fff;
	}

	.loan-info {
		background-color: #fff;
		padding: 16px;
		margin-bottom: 12px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.05);
	}

	.loan-info p {
		font-size: 16px;
		color: #333;
		margin-bottom: 8px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.loan-info .amount {
		font-size: 24px;
		font-weight: 600;
		color: #FF9800;
	}

	.interest-info {
		color: #ff9800 !important;
		font-size: 14px !important;
	}

	.warning-info {
		color: #f44336 !important;
		font-size: 14px !important;
		margin-top: 8px;
	}

	/****************** 提示信息部分 ******************/
	.notice-card {
		width: 100%;
		background-color: #fff;
		margin-bottom: 12px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.05);
		padding: 16px;
		box-sizing: border-box;
	}

	.notice-content {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.notice-content .material-icons {
		font-size: 24px;
		color: #FF9800;
		flex-shrink: 0;
	}

	.notice-content p {
		font-size: 14px;
		color: #666;
		margin: 0;
		line-height: 1.5;
	}

	/****************** 支付按钮部分 ******************/
	.payment-button {
		width: 100%;
		box-sizing: border-box;
		padding: 16px;
		background-color: #fff;
		position: fixed;
		bottom: 80px;
		left: 0;
		right: 0;
		box-shadow: 0 -2px 8px rgba(0,0,0,0.05);
	}

	.payment-button button {
		width: 100%;
		height: 48px;
		border: none;
		font-size: 16px;
		font-weight: 500;
		outline: none;
		border-radius: 12px;
		background: linear-gradient(135deg, #FF9800 0%, #FF5722 100%);
		color: #fff;
		cursor: pointer;
		transition: all 0.3s ease;
		box-shadow: 0 4px 12px rgba(255, 152, 0, 0.4);
	}

	.payment-button button:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.payment-button button:active:not(:disabled) {
		transform: scale(0.98);
		box-shadow: 0 2px 8px rgba(255, 152, 0, 0.3);
	}
</style>


